<template>
	<Dialog :show="true" :isH5="!isPC" :isHeaderShow="false" :isFooterShow="false" :background="false"
		@update:show="closeCreated">
		<div class="group" :class="[!isPC ? 'group-h5' : '']">
			<div class="group-box">
				<header class="group-box-header" :style="`padding-top: ${statusBarHeight}px`">
					<Icon :file="isPC ? closeIcon : backIcon" class="icon-close" @onClick="closeCreated" size="16px">
					</Icon>
					<h1 class="group-box-header-title">{{ headerTitle }}</h1>
				</header>
				<ul class="group-list" v-if="!groupInfo.isEdit">
					<li style="display: none;" class="group-list-item">
						<label class="group-list-item-label">{{ TUITranslateService.t('TUIGroup.群头像') }}</label>
						<Avatar :url="groupInfo.profile.avatar"></Avatar>
					</li>
					<ul>
						<li class="group-list-item" v-for="(item, index) in createInfo" :key="index">
							<label class="group-list-item-label">
								<text v-if="lang!='ru'">{{ item.name }} </text>
								<text v-else-if="lang=='ru'&&item.name=='群名称'">Название группы</text>
								<text v-else-if="lang=='ru'&&item.name=='群ID(选填)'">ID группы (необязательно)</text>
								<text v-else>{{ item.name }} </text>
							</label>
							<input v-if="isPC" type="text" v-model="groupInfo.profile[item.key]"
								:placeholder="item.placeholder" />
							<span v-else class="group-h5-list-item-content" @click="edit(item.key)">
								<p class="content">{{ groupInfo.profile[item.key] }}</p>
								<Icon :file="rightIcon"></Icon>
							</span>
						</li>
						<li class="group-list-introduction">
							<div class="group-list-item">
								<label class="group-list-item-label">
									<text v-if="lang!='ru'">{{TUITranslateService.t(`TUIGroup.群类型`)}}</text>
									<text v-if="lang=='ru'">Тип группы</text>
								</label>
								<GroupIntroduction v-if="isPC" :groupType="groupInfo.profile.type"
									@selectType="selected" />
								<span v-else class="group-h5-list-item-content" @click="edit('type')">
									<p class="content">{{ groupTypeDetail.label }}</p>
									<Icon :file="rightIcon"></Icon>
								</span>
							</div>
							<article class="group-h5-list-item-introduction" v-if="!isPC" style="display: none;">
								<label class="introduction-name">{{ groupTypeDetail.label }}：</label>
								<span class="introduction-detail">{{ groupTypeDetail.detail }}</span>
								<a :href="documentLink.product.url" target="view_window">
									{{ TUITranslateService.t(`TUIGroup.${groupTypeDetail.src}`) }}
								</a>
							</article>
						</li>

						<li class="group-list-item" style="margin-top: 30px;background-color: transparent;"
							v-if="lang!='ru'">
							<text v-if="name_select!=''" style="color: green;margin-left: 15px;"> 群名称：{{name_select}};
							</text>
							<text v-if="groupID_select!=''" style="color: orange; margin-left: 15px;">
								群ID：{{groupID_select}}; </text>
							<text v-if="leixing!=''" style="color: red;margin-left: 15px;"> 群类型：{{leixing}}; </text>
						</li>
						<li class="group-list-item" style="margin-top: 30px;background-color: transparent;"
							v-if="lang=='ru'">
							<text v-if="name_select!=''" style="color: green;margin-left: 15px;"> Название
								группы：{{name_select}}; </text>
							<text v-if="groupID_select!=''" style="color: orange;margin-left: 15px;"> ID группы
								(необязательно)：{{groupID_select}}; </text>
							<text v-if="leixing!=''" style="color: red;margin-left: 15px;"> Тип группы：{{leixing}};
							</text>
						</li>

					</ul>
				</ul>
				<!-- 修改群名称 -->
				<div class="group-list group-list-edit" v-else>
					<input v-if="groupInfo.groupConfig.type === 'input'" class="group-name-input" type="text"
						v-model="groupInfo.groupConfig.value"
						:placeholder="TUITranslateService.t(`TUIGroup.${groupInfo.groupConfig.placeholder}`)" />
					<GroupIntroduction v-else class="group-introduction-list" :groupType="groupInfo.groupConfig.value"
						@selectType="selected" />
				</div>
				<footer class="group-profile-footer">
					<button v-if="isPC && !groupInfo.isEdit" class="btn-default" @click="closeCreated">
						<text v-if="lang!='ru'">{{ TUITranslateService.t('TUIGroup.取消') }}</text>
						<text v-if="lang=='ru'">Нет</text>
					</button>
					<button class="btn-submit" :disabled="submitDisabledStatus" @click="submit" style="width: 300px;">
						<text v-if="lang!='ru'">{{ TUITranslateService.t('TUIGroup.确认') }}</text>
						<text v-if="lang=='ru'">Подтвердить</text>
					</button>
				</footer>
			</div>
		</div>
	</Dialog>
</template>

<script lang="ts" setup>
	import TUIChatEngine, {
		TUITranslateService,
		TUIGroupService,
		TUIStore,
		StoreName,
	} from "@tencentcloud/chat-uikit-engine";
	import { computed, reactive, ref, watchEffect } from "../../../adapter-vue";
	import documentLink from "../../../utils/documentLink";
	import { isPC } from "../../../utils/env";
	import Icon from "../../common/Icon.vue"
	import backIcon from "../../../assets/icon/back.svg";
	import closeIcon from "../../../assets/icon/icon-close.svg";
	import rightIcon from "../../../assets/icon/right-icon.svg";
	import GroupIntroduction from "./group-introduction/index.vue";
	import { groupIntroConfig, findGroupIntroConfig, groupIntroConfig_ru } from "./group-introduction/config";
	import Dialog from "../../common/Dialog/index.vue";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import Avatar from "../../common/Avatar/index.vue"
	import Server from "../server";
	import { IUserProfile } from "../../../interface";
	const TUIGroupServer = Server.getInstance();
	const TUIConstants = TUIGroupServer.constants;
	const lang = getApp().globalData.lang;
	let leixing = ref('')
	let groupID_select = ref('')
	let name_select = ref('')
	const groupInfo = reactive<any>({
		profile: {
			groupID: '',
			name: '',
			type: groupIntroConfig[0].type,
			type_ru: groupIntroConfig_ru[0].type,
			avatar: groupIntroConfig[0].icon,
			introduction: '',
			notification: '',
			// joinOption: '',
			memberList: [],
			isSupportTopic: false,
		},
		groupConfig: {
			title: '',
			value: '',
			key: '',
			type: '',
			placeholder: '',
		},
		isEdit: false,
	});

	let systemInfo = uni.getSystemInfoSync();
	let statusBarHeight = systemInfo.statusBarHeight;

	watchEffect(() => {
		const params = TUIGroupServer.getOnCallParams(TUIConstants.TUIGroup.SERVICE.METHOD.CREATE_GROUP);
		groupInfo.profile.memberList = params.memberList;
		groupInfo.groupConfig.title = params.title;
	})

	const groupTypeDetail = computed(() => {
		return findGroupIntroConfig(groupInfo.profile.type);
	});

	const headerTitle = computed(() => {

		let name = '添加群聊';
		if (lang == 'ru') {
			name = 'Добавить групповой чат'
		}

		if (groupInfo.isEdit) {
			name = groupInfo.groupConfig.title;
		}
		return TUITranslateService.t(`TUIGroup.${name}`)
	});

	const createInfo = computed(() => {
		const groupNameInput = {
			name: TUITranslateService.t("TUIGroup.群名称"),
			key: "name",
			placeholder: TUITranslateService.t("TUIGroup.请输入群名称"),
		};
		const groupIDInput = {
			name: `${TUITranslateService.t("TUIGroup.群ID")}(${TUITranslateService.t("TUIGroup.选填")})`,
			key: "groupID",
			placeholder: TUITranslateService.t("TUIGroup.请输入群ID"),
		};
		return groupInfo.profile.type === TUIChatEngine.TYPES.GRP_COMMUNITY
			? [groupNameInput]
			: [groupNameInput, groupIDInput];
	});

	const submitDisabledStatus = computed(() => {
		return groupInfo.profile.name === '' && !groupInfo.isEdit;
	});

	let backupsType = ref<any>("Private");

	const selected = (type : any) => {
		backupsType.value = type;

	};

	const createGroup = async (options : any) => {
		try {
			options.memberList = options.memberList.map((item : IUserProfile) => {
				return { userID: item.userID };
			});
			if (options.type === TUIChatEngine.TYPES.GRP_COMMUNITY) {
				delete options.groupID;
			}
			const res = await TUIGroupService.createGroup(options);
			const { type } = res.data.group;
			if (type === TUIChatEngine.TYPES.GRP_AVCHATROOM) {
				await TUIGroupService.joinGroup({
					groupID: res.data.group.groupID,
					applyMessage: '',
				});
			}
			handleCompleteCreate(res.data.group);
			// Toast({
			// 	message: 'SUCCESS',
			// 	//message: TUITranslateService.t("TUIGroup.群组创建成功"),
			// 	type: TOAST_TYPE.SUCCESS
			// });
		} catch (err : any) {
			if (err.message.indexOf("group name is too long") >= 0) {
				Toast({
					message: lang !== 'ru' ? "群名称过长" : "Слишком длинное название группы",
					type: TOAST_TYPE.ERROR
				});
			} else {
				Toast({
					message: lang !== 'ru' ? "群ID重复" : "Повтор ID группового чата",
					type: TOAST_TYPE.ERROR
				});
			}
		}
	}

	const submit = () => {
		const { profile } = groupInfo;
		if (groupInfo.isEdit) {
			groupInfo.profile[groupInfo.groupConfig.key] = groupInfo.groupConfig.value;

			if (groupInfo.groupConfig.key == 'groupID') {
				groupID_select.value = groupInfo.groupConfig.value;
			}
			if (groupInfo.groupConfig.key == 'name') {
				name_select.value = groupInfo.groupConfig.value;
			}
			if (groupInfo.groupConfig.key == 'type') {
				if (groupInfo.profile.type !== backupsType.value) {
					groupInfo.profile.type = backupsType.value;
					groupInfo.profile.avatar = findGroupIntroConfig(backupsType.value).icon;
					if (groupInfo.isEdit) {
						groupInfo.groupConfig.value = backupsType.value;
					}
				}
				if (groupInfo.groupConfig.value == 'Private') {
					if (lang == 'zh') {
						leixing.value = '工作群';
					} else {
						leixing.value = 'Рабочая группа друзей';
					}
				}

				if (groupInfo.groupConfig.value == 'Public') {
					if (lang == 'zh') {
						leixing.value = '陌生人社交群';
					} else {
						leixing.value = 'Группа незнакомых людей';
					}
				}
				if (groupInfo.groupConfig.value == 'ChatRoom') {
					if (lang == 'zh') {
						leixing.value = '临时会议群';
					} else {
						leixing.value = 'Предварительное совещание';
					}
				}
				if (groupInfo.groupConfig.value == 'AVChatRoom') {
					if (lang == 'zh') {
						leixing.value = '直播群';
					} else {
						leixing.value = 'Группа прямых трансляций';
					}
				}
				if (groupInfo.groupConfig.value == 'Community') {
					if (lang == 'zh') {
						leixing.value = '社群';
					} else {
						leixing.value = 'Сообщество';
					}
				}
			}

			return groupInfo.isEdit = !groupInfo.isEdit;
		} else {
			createGroup(profile);
		}
	};


	const closeCreated = () => {
		if (groupInfo.isEdit) {
			return groupInfo.isEdit = !groupInfo.isEdit;
		}
		handleCompleteCreate(null);
	};

	const edit = (label : string) => {
		groupInfo.isEdit = !groupInfo.isEdit;
		groupInfo.groupConfig.key = label;
		groupInfo.groupConfig.value = (groupInfo.profile as any)[label];

		var t1 = '设置群名称'
		var t2 = '请输入群名称'
		var t3 = '设置群ID'
		var t4 = '请输入群ID'
		var t5 = '选择群类型'
		if (lang == 'ru') {
			t1 = 'Задайте название группы'
			t2 = 'Введите название группы'
			t3 = 'Установите ID группы'
			t4 = 'Введите ID группы'
			t5 = 'Тип группы'
		}


		switch (label) {
			case 'name':
				groupInfo.groupConfig.title = t1;
				groupInfo.groupConfig.placeholder = t2;
				groupInfo.groupConfig.type = 'input';
				break;
			case 'groupID':
				groupInfo.groupConfig.title = t3;
				groupInfo.groupConfig.placeholder = t4;
				groupInfo.groupConfig.type = 'input';
				break;
			case 'type':
				groupInfo.groupConfig.title = t5;
				groupInfo.groupConfig.type = 'select';
				break;
		}
	};

	const handleCompleteCreate = (group : any) => {
		TUIStore.update(StoreName.GRP, "isShowCreateComponent", false);
		const callback = TUIGroupServer.getOnCallCallback(TUIConstants.TUIGroup.SERVICE.METHOD.CREATE_GROUP);
		callback && callback(group);
	}
</script>
<style lang="scss" scoped src="./style/index.scss"></style>